package com.tanhua.api.mongdb;

import com.tanhua.domain.mogo.UserLike;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override  //喜欢的
    public Long findloveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return count;
    }

    @Override
    public Long findfanCount(Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return count;
    }

    @Override
    public PageBeanVo findeachLovePage(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        Long count = mongoTemplate.count(query, UserLike.class);
        return new PageBeanVo(page,pagesize,count,userLikeList);
    }

    @Override
    public PageBeanVo findfanPage(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        Long count = mongoTemplate.count(query, UserLike.class);
        return new PageBeanVo(page,pagesize,count,userLikeList);

    }

    @Override
    public void removeFans(Long fansId, Long userId) {

        Query query = new Query(Criteria.where("likeUserId").is(userId)
        .and("userId").is(fansId));
        mongoTemplate.remove(query,UserLike.class);
    }

    @Override
    public void addUserLike(Long userId, Long loveId) {
        UserLike userLike = new UserLike();
        userLike.setCreated(System.currentTimeMillis());
        userLike.setLikeUserId(userId);
        userLike.setUserId(loveId);

        mongoTemplate.insert(userLike);
    }
}
